import userapi from '../../../config/api/userapi' // 引入api接口管理文件
var WxNotificationCenter = require("../../../config/WxNotificationCenter");

import {
  baseUrl
} from '../../../config/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    obj: null,
    id: null,
    imgUrl: null,
    name: null,
    phone: null,
    openId: null,
    ruserRoles: [],
    suppliesArr: [{
      id: 1,
      name: '管理员',
      checked: false
    },
    {
      id: 2,
      name: '职员',
      checked: false
    },
    {
      id: 3,
      name: '司机',
      checked: false

    },
    {
      id: 4,
      name: '商家',
      checked: false

    },
    {
      id: 5,
      name: '审核员',
      checked: false

    },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let itemss = options["item"];
    if (itemss) {
      //编辑
      itemss = decodeURIComponent(itemss);
      let obj = JSON.parse(itemss);
      //获取用户详情
      this.setData({
        obj: obj
      })
      this.getuserinfo(obj);
    }

  },
  getuserinfo(obj) {

    let data = {};
    if (obj["openId"]) {
      data['openId'] = obj["openId"];
    } else if (obj["phone"]) {
      data['phone'] = obj["phone"];
    }
    let vm = this;
    userapi.getDataByOpenId(data, function (res) {
      let data = res.data.data;
      console.log(data);
      vm.setData({
        id: data.id,
        imgUrl: data.imgUrl,
        name: data.name,
        phone: data.phone,
        openId: data.openId,
      })
      // 回显职能
      let ruserRoles = data.ruserRoles;
      let zhinengs = ruserRoles.map(res => {
        return res.roleId * 1;
      })
      let array = vm.data.suppliesArr;
      console.log(zhinengs);
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (zhinengs.indexOf(element.id) != -1) {
          element.checked = true;
        }
      }
      vm.setData({
        suppliesArr: array,
      })
    });
  },

  //处理文本双向绑定问题
  onChange(e) {
    console.log(e.detail.value) //input 的 value
    console.log(e.currentTarget.dataset.prop) //data-prop 绑定的字符串，以此来确定改变的是哪个变量
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value
    })
  },
  //处理带数组类型的绑定
  moretypechange(e) {
    let arr = this.data[e.currentTarget.dataset.arrdata];
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value
    })
  },
  // 指着选择
  checkboxChange(e) {
    //更新数组
    let zhinengs = e.detail.value.map(res => {
      return res * 1;
    })
    let array = this.data.suppliesArr;
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      if (zhinengs.indexOf(element.id) != -1) {
        element.checked = true;
      } else {
        element.checked = false;
      }
    }
    this.setData({
      suppliesArr: array,
    })
  },
  // 上传文件
  clickupfile() {
    let vm = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为 img 标签的 src 属性显示图片
        const tempFilePaths = res.tempFiles[0].tempFilePath;
        let url = baseUrl + 'aliyunFile/uploadFile';
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          url: url, //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          success(res) {

            const data = res.data
            let urlpath = JSON.parse(data)["data"];
            vm.setData({
              imgUrl: urlpath
            })
          },
          fail(error) {
            console.log(error);
          },
          complete() {
            console.log("complete");
            wx.hideLoading({
              success: (res) => { },
            })
          }
        })
      }
    })


  },
  clickdel(e) {
    let content = `确定要删除么?`
    let vm = this;
    wx.showModal({
      title: '提示',
      content: content,
      success(res) {
        if (res.confirm) {
          //开始删除
          wx.showLoading({
            title: '取消中...',
          })
          let data = {};
          if (vm.data.openId) {
            data['openId'] = vm.data.openId;
          } else if (vm.data.phone) {
            data['phone'] = vm.data.phone;
          }
          userapi.userdel(data, function (res) {
            wx.hideLoading({
              success: (res) => { },
            })
            if (res.data.status == 200) {
              wx.showModal({
                title: '删除成功',
                showCancel: false,
                success: (result) => { },
                fail: (res) => { },
                complete: (res) => {
                  vm.reloaduppage();
                },
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "none"
              })
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  clicktijiao() {

    let keyandff = {
      "imgUrl": "请上传照片",
      "name": "请输入姓名",
      "phone": "请输入电话号",
    }
    let keys = Object.keys(keyandff);
    for (let index = 0; index < keys.length; index++) {
      const element = keys[index];
      if (!this.data[element]) {
        wx.showToast({
          title: keyandff[element],
          icon: 'none'
        })
        return;
      }
    }

    let obj = {
      "imgUrl": this.data.imgUrl,
      "name": this.data.name,
      "phone": this.data.phone,
    }
    //处理权限
    let qxarr = [];
    let array = this.data.suppliesArr;
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      if (element.checked) {
        qxarr.push({ id: element.id });
      }
    }

    let url = userapi.save;
    if (this.data.id) {
      url = userapi.userBindRole;
      obj["id"] = this.data.id;
      obj['roles'] = qxarr;
    }
    let vm = this;
    wx.showLoading({
      title: '加载中...',
    })
    url(obj, function (res) {
      wx.hideLoading({
        success: (res) => { },
      })
      if (res.data.status == 200) {
        wx.showModal({
          title: '提交成功',
          showCancel: false,
          success: (result) => { },
          fail: (res) => { },
          complete: (res) => {
            vm.reloaduppage();
          },
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },

  //刷新上一页
  reloaduppage() {
    WxNotificationCenter.postNotificationName("getuserlist");
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onUnload() {
    var that = this
    WxNotificationCenter.removeNotification('selectdrivers', that)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})